import React, { useContext, useEffect } from 'react';
import { DisplayTable, EditableTable } from './components';
import TableContext from './components/TableContext';
import { STONG_TABLE } from './config';
import { UPDATE_ISCANEDIT, UPDATE_NAME } from './context/table';
import type { AnyObject, StongTableProps, TableContextRef } from './type';
export { DisplayTable, EditableTable, TableModal } from './components';
export type { Props as TableModalProps } from './components/TableModal';
export type {
  Column,
  ColumnMeta,
  CurOperateInfo,
  DisplayTableProps,
  EditableTableProps,
  FilterItem,
  FilterList,
  GetModalDataResponse,
  Rule,
  SelectTableRef,
  StongTableProps,
  TableContextRef,
  TableModal as TableModalType,
} from './type';

function StongTable<T extends AnyObject>(
  props: StongTableProps<T>,
  ref: React.ForwardedRef<TableContextRef<T>>,
) {
  const { isCanEdit, ...tableProps } = props;
  const { table: tableContextInfo, dispatch } = useContext(props.context);
  useEffect(() => {
    if (!tableContextInfo.name)
      dispatch({ type: UPDATE_NAME, payload: STONG_TABLE });
  }, [tableContextInfo.name]);
  useEffect(() => {
    dispatch({ type: UPDATE_ISCANEDIT, payload: isCanEdit });
  }, [isCanEdit]);
  return isCanEdit ? (
    <EditableTable {...tableProps} ref={ref} />
  ) : (
    <DisplayTable {...tableProps} ref={ref} />
  );
}

function StongTableontext<T extends AnyObject>(
  props: StongTableProps<T>,
  ref: React.ForwardedRef<TableContextRef<T>>,
) {
  return <TableContext {...props} Table={StongTable} ref={ref} />;
}

export default React.forwardRef(StongTableontext) as <T>(
  props: StongTableProps<T> & { ref?: React.ForwardedRef<TableContextRef<T>> },
) => ReturnType<typeof StongTableontext>;
